<?php

namespace App\Http\Controllers\Personal;

use App\Facades\Site;
use App\Http\Requests\Common\Captcha\SmsCodeRequest;
use App\Models\Personal\PersonalTrialError;
use App\Models\Personal\PersonalLoginRecord;
use Illuminate\Http\Request;
use App\Http\Requests\Personal\Login\AjaxLoginRequest;
use App\Http\Requests\Personal\Login\AjaxMobileLoginRequest;
use App\Models\Personal\PersonalUser;
use Auth, Sms;

class LoginController extends CommonController{
    /**
     * ajax登录
     * @param AjaxLoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxLogin(AjaxLoginRequest $request){
        $input = $request->except('_token');
        //用户和手机登录多可以
        $remember = !empty($input['remember']) ? $input['remember'] : false;
        if(Auth::guard('personal')->attempt(['username' => $input['username'], 'password' => $input['password']], $remember)){
            $user = auth()->guard('personal')->user();
            //登录记录表
            $this->loginRecord($user);

            return response()->json(['status' => '0', 'msg' => '登录用户成功!']);
        }else if(Auth::guard('personal')->attempt(['mobile' => $input['username'], 'password' => $input['password']], $remember)){
            $user = auth()->guard('personal')->user();
            //登录记录表
            $this->loginRecord($user);

            return response()->json(['status' => '0', 'msg' => '登录用户成功!']);
        }else{
            //个人试错登录记录
            $this->trialErrorRecord($input);
            return response()->json(['status' => '1', 'msg' => '用户名或者密码错误!']);
        }
    }

    /**
     * ajax手机登录
     * @param AjaxMobileLoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxMobileLogin(AjaxMobileLoginRequest $request){
        $input = $request->except('_token');
        //手机登录
        if(Auth::guard('personal')->check()){
            return response()->json(['status' => '0', 'msg' => '此手机号码已经登录!']);
        }else{
            $user = PersonalUser::where('mobile', $input['mobile'])->first();
            //删除验证码的session数据
            $request->session()->forget('mobile_verification');
            $request->session()->forget('mobile_verification_code');
            if(Auth::guard('personal')->loginUsingId($user->uid)){
                $user = auth()->guard('personal')->user();
                //登录记录表
                $this->loginRecord($user);
                return response()->json(['status' => '0', 'msg' => '登录用户成功!']);
            }else{
                return response()->json(['status' => '1', 'msg' => '手机号码和验证号码不匹配!']);
            }
        }
    }

    /**
     * 个人试错记录信息表
     * @param $userInfo
     */
    public function trialErrorRecord($input){
        //试错记录表
        $trial = array();
        $trial['username'] = $input['username'];
        $trial['password'] = $input['password'];
        $trial['company_login_ip'] = getIp();
        //登录记录表
        PersonalTrialError::create($trial);
    }

    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($userInfo){
        //登录记录表
        $record = array();
        $record['uid'] = $userInfo->uid;
        $record['personal_login_ip'] = getIp();
        $record['personal_login_time'] = date('Y-m-d H:i:s', time());
        $record['login_type'] = 2;
        $record['type'] = 1;
        //登录记录表
        PersonalLoginRecord::create($record);

        //更新用户表记录
        $userInfo->last_login_time = date('Y-m-d H:i:s', time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();
    }

    /**
     * 获取短信验证码
     * @param SmsCodeRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxMobLoginCode(SmsCodeRequest $request){
        $mobileNum = $request->input('mobile');
        $result = PersonalUser::where('mobile', $mobileNum)->first();
        if($result){
            //设置session
            $request->session()->put('mobile_verification_code', rand(1000, 9999));
            $request->session()->put('mobile_verification', $mobileNum);
            //模板参数
            $smsParam = array(
                'product' => Site::get('webname'),
                'code' => (string)session('mobile_verification_code')
            );
            $sendResult = Sms::codeSend($mobileNum, $smsParam);
            //返回对象
            if(is_object(@$sendResult->result) && $sendResult->result->err_code == '0'){
                return response()->json(['status' => '1', 'msg' => '发送短信成功']);
            }else{
                return response()->json(['status' => '0', 'msg' => '一分钟之内只能发一次,或者您发送的次数已经达到上限']);
            }
        }else{
            return response()->json(['status' => '2', 'msg' => '此手机号码还没注册，请先注册']);
        }
    }
}